﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using XYAC.Framework.MonitorTireMaterialOnline.Entities;
using XYAC.Framework.MonitorTireMaterialOnline.Extensions;
using XYAC.Framework.MonitorTireMaterialOnline.IServices;
using XYAC.Framework.MonitorTireMaterialOnline.LocalData.Context;
using XYAC.Framework.MonitorTireMaterialOnline.LocalData.Models;
using XYAC.Framework.MonitorTireMaterialOnline.OracleRemoteDB;

namespace XYAC.Framework.MonitorTireMaterialOnline.Services
{
    internal class YB_PROCESS_STEPService : ServiceBase<int, OracleMesContext>, IYB_PROCESS_STEPService
    {

        private const string __REMOTE_SYNC_STATE_PENDING = "PENDING";
        private const string __REMOTE_SYNC_STATE_COMPLETE = "COMPLETE";
        private const string __REMOTE_SYNC_STATE_PLANED = "PLANED";
        private const string __TABLENAME_SpecVal = "SpecVal";
        private const string __TABLENAME_WeightData = "WeightData";

        public YB_PROCESS_STEPService(IOptionsMonitor<AppConfig> appConfig, ILogger<YB_PROCESS_STEPService> logger, IServiceProvider provider) : base(appConfig, logger, provider)
        {
            //this.MesDb = provider.GetService<OracleMesContext>();
            //this.LocalDb = provider.GetService<LocalDataContext>();
            this.Logger = logger;
        }

        //public OracleMesContext MesDb { get; }
        //public LocalDataContext LocalDb { get; }
        public ILogger Logger { get; }

        public YB_PROCESS_STEP From(SpecValTable data)
        {
            return new YB_PROCESS_STEP
            {
                RECORD1 = data.ID.ToString(),
                RECORD56 = data.BanZu.ToString(),
                RECORD_DATE = data.StartTime == null ? (DateTime?)null : DateTime.Parse(data.StartTime), // 假设StartTime是一个可以转换为DateTime的字符串
                PART_NUMBER = data.ProfileName.ToString(),
                //PART_NUMBER = data.SpecNo.ToString(),
                RECORD4 = data.ProfileType.ToString(),
                RECORD5 = data.RimHeight.ToString(),
                RECORD6 = data.RimTol.ToString(),
                RECORD7 = data.TotalWidth.ToString(),
                RECORD8 = data.WidthTol.ToString(),
                RECORD9 = data.AreaDiff.ToString(),
                RECORD10 = data.TextNo.ToString(),
                RECORD11 = data.ShoulderWidth.ToString(),
                RECORD12 = data.ShoulderWidthTol.ToString(),
                RECORD13 = data.ShoulderHeight.ToString(),
                RECORD14 = data.ShoulderHeightTol.ToString(),
                RECORD15 = data.jiao.ToString(),
                RECORD16 = data.DateTimePicker.ToString(), // 假设DateTimePicker是一个字符串
                RECORD17 = data.GJD.ToString(),
                RECORD18 = data.ResultPercent.ToString(),
                RECORD19 = data.IntervalWidth.ToString(),
                RECORD20 = data.IXReference.ToString(),
                RECORD21 = data.SpecVal.ToString(),
                RECORD22 = data.BottomHeightVals.ToString(),
                RECORD23 = data.KeyPoints.ToString(),
                RECORD24 = data.TestResult.ToString(),
                RECORD25 = data.AlarmPoints.ToString(),
                RECORD26 = data.BanZu.ToString(),
                RECORD27 = data.RimTol.ToString(),
                //EQP = data.MachineNo,
                //PLAN_ID = data.PlanNo,
                //RECEIVE_FLAG = data.Status, // 字面值
                //RECORD28 = data.TableName, // 字面值
                //RECORD30 = data.Sn
            };
        }
        public SpecValTable ToSpecVal(YB_PROCESS_STEP data)
        {


            return new SpecValTable
            {
                ID = data.RECORD1 == null ? 0 : Convert.ToInt32(data.RECORD1),
                //BZ = data.RECORD2,
                StartTime = data.RECORD_DATE?.ToString() ?? data.RECORD_DATE.Value.ToString("yyyy-MM-dd HH:mm:ss"), // 假设需要特定格式
                ProfileName = data.PART_NUMBER,
                ProfileType = data.RECORD4 == null ? (short)0 : Convert.ToInt16(data.RECORD4),
                RimHeight = data.RECORD5 == null ? 0f : Convert.ToSingle(data.RECORD5),
                RimTol = data.RECORD6 == null ? 0f : Convert.ToSingle(data.RECORD6),
                TotalWidth = data.RECORD7 == null ? 0f : Convert.ToSingle(data.RECORD7),
                WidthTol = data.RECORD8 == null ? 0f : Convert.ToSingle(data.RECORD8),
                AreaDiff = data.RECORD9 == null ? 0f : Convert.ToSingle(data.RECORD9),
                TextNo = data.RECORD10.ToString(),
                ShoulderWidth = data.RECORD11 == null ? 0f : Convert.ToSingle(data.RECORD11),
                ShoulderWidthTol = data.RECORD12 == null ? 0f : Convert.ToSingle(data.RECORD12),
                ShoulderHeight = data.RECORD13 == null ? 0f : Convert.ToSingle(data.RECORD13),
                ShoulderHeightTol = data.RECORD14 == null ? 0f : Convert.ToSingle(data.RECORD14),
                jiao = data.RECORD15.ToString(),
                DateTimePicker = data.RECORD16.ToString(), // 假设需要保持字符串格式
                GJD = data.RECORD17.ToString(),
                ResultPercent = data.RECORD18 == null ? 0 : Convert.ToInt32(data.RECORD18),
                IntervalWidth = data.RECORD19 == null ? 0f : Convert.ToSingle(data.RECORD19),
                IXReference = data.RECORD20 == null ? 0f : Convert.ToSingle(data.RECORD20),
                SpecVal = data.RECORD21.ToString(),
                BottomHeightVals = data.RECORD22.ToString(),
                KeyPoints = data.RECORD23.ToString(),
                TestResult = data.RECORD24.ToString(),
                AlarmPoints = data.RECORD25.ToString(),
                BanZu = data.RECORD26.ToString(),
            };
        }



        internal int Add(YB_PROCESS_STEP insertData)
        {
            using (var scope = Provider.CreateScope())
            {
                var MesDb = scope.ServiceProvider.GetService<OracleMesContext>();

                MesDb.Add(insertData);
                return MesDb.SaveChanges();
            }
        }


        /// <summary>
        /// 更新本地数据库中间表状态为1,上传生产数据至mes库
        /// </summary>
        /// <param name="specVal"></param>
        /// <param name="inspectModel"></param>
        /// <returns></returns>
        internal int SyncRemoteProduceData(SpecValTable specVal, YB_LOT_INSPECT_Local inspectModel)
        {
            using (var scope = Provider.CreateScope())
            {
                var MesDb = scope.ServiceProvider.GetService<OracleMesContext>();
                var LocalDb = scope.ServiceProvider.GetService<LocalDataContext>();
                int ret = 0;


                using (var remoteTransaction = MesDb.Database.BeginTransaction())
                {
                    using (var localTranscation = LocalDb.Database.BeginTransaction())
                    {

                        try
                        {
                            var specValStep = this.From(specVal);
                            specValStep.PLAN_ID = inspectModel.PLANID;
                            specValStep.EQP = inspectModel.EQP;
                            specValStep.RECEIVE_FLAG = __REMOTE_SYNC_STATE_PENDING;
                            specValStep.RECORD29 = __TABLENAME_SpecVal;

                            MesDb.YB_PROCESS_STEP.Add(specValStep);

                            inspectModel.RemoteSyncDate = DateTime.Now;
                            inspectModel.RemoteSyncState = true;//将本地数据状态RemoteSyncState=true

                            LocalDb.YB_LOT_INSPECT.Update(inspectModel);

                            int tempRetRemote = MesDb.SaveChanges();
                            int tempRetLocal = LocalDb.SaveChanges();
                            if (tempRetLocal == tempRetRemote)
                            {
                                remoteTransaction.Commit();
                                localTranscation.Commit();
                                ret = tempRetLocal;
                            }
                        }
                        catch (Exception)
                        {
                            remoteTransaction.Rollback();
                            localTranscation.Rollback();
                        }
                    }

                }
                return ret;
            }
        }
    }
}
